<?php

namespace App\Http\Controllers\Api;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Transformers\CategoryTransformer;
use App\Http\Requests\Api\CategoryRequest;

class CategoriesController extends Controller
{
    public function search(Request $request, Category $category)
    {
        $per_page = $request->input('per_page', 20);
        $query = $category->query();

        $query->where('delflag', false);

        if ($name = $request->name) {
            $query=$query->where('name', 'like', "%{$request->name}%");
        }

        if ($orderBy = $request->orderBy) {
            $query=$query->ordered();
        } else {
            $query=$query->recent();
        }

        $categories = $query->paginate($per_page);

        return $this->response->paginator($categories, new CategoryTransformer());
    }

    public function index(Request $request, Category $category)
    {
        $per_page = $request->input('per_page', 20);
        $query = $category->query();

        $query->where('delflag', false);

        if ($orderBy = $request->orderBy) {
            $query=$query->ordered();
        } else {
            $query=$query->recent();
        }

        $categories = $query->paginate($per_page);

        return $this->response->paginator($categories, new CategoryTransformer());
    }

    public function show(Category $category)
    {
        return $this->response->item($category, new CategoryTransformer());
    }

    public function store(CategoryRequest $request, Category $category)
    {

        $this->authorize('update', $category);

        $category->fill($request->all());
        $category->save();

        return $this->response->item($category, new CategoryTransformer())
            ->setStatusCode(201);
    }

    public function update(CategoryRequest $request, Category $category)
    {
        $this->authorize('update', $category);

        $category->update($request->all());

        return $this->response->item($category, new CategoryTransformer());
    }

    public function destroy(Category $category)
    {
        $this->authorize('destroy', $category);

        $category->delflag=true;
        $category->save();
        return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag'=>true,
            ],
            'message'=>'删除成功',
        ])->setStatusCode(200);
    }
}